import commonservice from './commonservice.js'

const webRequest = function(opt) { //  url, method, info = null
	opt = opt || {};
	opt.url = opt.url || '';
	opt.data = opt.data || null;
	opt.method = opt.method || 'GET';
	opt.method = opt.method.toUpperCase(); //转换成大写
	opt.header = opt.header || {
		'Authorization': 'Bearer ' + getApp().$store.state.accessToken
	};

	if (opt.method == 'GET' && opt.data != null) {
		opt.url += "?1=1";
		for (var item in info) {
			//console.log(item)
			opt.url += "&" + item + "=" + info[item];
		}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: commonservice.WEBSITE + opt.url,
			header: opt.header,
			method: opt.method,
			data: opt.data,
			success: function(res) {
				console.log(JSON.stringify(res))
				if (res.statusCode == 200 || res.statusCode == 400) {
					resolve(res)
				} else if (res.statusCode == 401) {
					var pages = getCurrentPages() // 获取栈实例
					//let currentRoute  = pages[pages.length-1].route; // 获取当前页面路由
					let currentPage = pages[pages.length-1]['$page']['fullPath'] //当前页面路径(带参数)
					console.log("___"+currentPage)
					getApp().$store.state.accessToken = ''; 
					getApp().$store.state.hasLogin=false;
					getApp().$store.state.gotoinfo.pageurl=currentPage;//为了设置跳转回当前页
					uni.showToast({
						title: '登录已失效',
						icon: 'none'
					});
					uni.navigateTo({
						url: '/pages/login/login'
					});  
				} else {
					uni.showToast({
						title: '状态码：' + res.statusCode,
						icon: 'none'
					});
				}
			},
			fail: function(ex) {
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				});
			}
		})

	})
}

export default {
	webRequest: webRequest
}
